const user = {
  async GetCount(data) {
    let query =
      "SELECT COUNT(1) AS count FROM user_auth ua " +
      "LEFT JOIN user_info ui ON ua.user_info_id = ui.id ";
    let whereClauses = [];
    let params = [];
    if (data.login_type !== undefined && data.login_type !== 0) {
      whereClauses.push("login_type = ?");
      params.push(data.login_type);
    }
    if (data.nickname !== undefined && data.nickname !== "") {
      whereClauses.push("nickname LIKE ?");
      params.push("%" + data.nickname + "%");
    }

    if (whereClauses.length > 0) {
      query += "WHERE " + whereClauses.join(" AND ");
    }

    const [rows] = await global.mysqlPool.execute(query, params);
    let count = 0;
    if (rows.length > 0) {
      count = rows[0].count;
    }
    return count;
  },
  async GetList(data) {
    let mainQuery = `
      SELECT ua.id, ua.user_info_id,  ua.login_type, ua.ip_address, ua.ip_source, 
             ua.created_at, ua.last_login_time, ui.is_disable ,ui.avatar,ui.nickname
      FROM (
        SELECT user_info.id, user_info.avatar, user_info.nickname, user_info.is_disable 
        FROM user_info 
        WHERE 1=1 
    `;

    let conditions = [];
    let params = [];

    if (data.login_type !== undefined && data.login_type !== 0) {
      conditions.push(
        "id IN (SELECT user_info_id FROM user_auth WHERE login_type = ?)"
      );
      params.push(data.login_type);
    }
    if (data.nickname) {
      conditions.push("nickname LIKE ?");
      params.push("%" + data.nickname + "%");
    }

    if (conditions.length > 0) {
      mainQuery += " AND " + conditions.join(" AND ");
    }

    mainQuery += `) ui 
                  LEFT JOIN user_auth ua ON ua.user_info_id = ui.id`;

    mainQuery += ` LIMIT ? OFFSET ?`;

    params.push(data.page_size, data.page_size * (data.page_num - 1));

    const [rows] = await global.mysqlPool.execute(mainQuery, params);

    for (const row of rows) {
      row.name = row.nickname;
    }
    return rows;
  },
};

module.exports = user;
